import store from "~/store";
import { Message } from 'element-ui'
import { callState } from "~/utils/call-center/state";

let msg: any = null;
let hasWaInit = false;

export const mountWebAgent = (options, callback?: (data) => void) => {
  const WebAgent = (window as any).WebAgent
  loginWebAgent()

  function loginWebAgent () {
    // 非自动登录入口
    initWebAgent().then(() => {
      const loginParam = {
        entId: options.entId,
        agentId: options.agentId,
        agentPassword: options.agentPassword,
        agentNumber: options.agentNumber.includes('sip') ? options.agentNumber : 'sip:' + options.agentNumber,
        // entId: '2107120002',
        // agentId: '2002',
        // agentPassword: '2002',
        // agentNumber: 'sip:660210002',
        isLocking: (data) => {
          console.log('[CDesk] 当前置忙置闲状态不能使用', data);
        },
        unLocking: (a, b) => {
          console.log('unLocking data', a, b);
          store.commit('call-center/updateCurrentStatus', a)
        }
      };

      WebAgent.multiChannelLogin(WebAgent, loginParam);
    });
  };


  function initWebAgent () {
    return new Promise((res, rej) => {
      // 已经初始化过了，就不再初始化，避免socket重复创建、事件重复注册等异常场景
      if (hasWaInit) {
        return res(true);
      }

      // debugger

      WebAgent.init({
        useLocal: false,
        loadBootstrap: false,
        WaParams: {
          ui: false,
          sipUseCphone: "sip",
        },
        isUseCChat: true,
        ChatParams: {
          selectorName: "#content",
          isCheckWord: true,
        },
        callback: () => {
          // 这里进行login操作
          // WebAgent.multiChannelLogin(WebAgent, {
          //   entId: options.entId,
          //   agentId: options.agentId,
          //   agentPassword: options.agentPassword,
          //   agentNumber: options.agentNumber.includes('sip') ? options.agentNumber : 'sip:' + options.agentNumber,
          //   isLocking: (data) => {
          //     console.log('[CDesk] 当前置忙置闲状态不能使用', data);
          //   },
          //   unLocking: (a, b) => {
          //     console.log('unLocking data', a, b);
          //     store.commit('call-center/updateCurrentStatus', a)
          //   }
          // });
          let outBoundNumList = ''
          //socket异常断开
          WebAgent.registerEventHandler((data) => {
            const { errorMessage, ext } = data || {}
            console.log('registerEventHandler data', data.ext);
            if (errorMessage?.includes('异常断开')) Message.error('socket异常断开')
            // handle data when events received
            if (Reflect.ownKeys(ext).length) {
              if (data.ext.outBoundNumList) outBoundNumList = data.ext.outBoundNumList
              data.ext.outBoundNumList = outBoundNumList
              store.commit('call-center/updateEventData', data)
            }

          });
          //Cphone断开连接
          WebAgent.ChatRegisterEvent('butelAjaxError', function (data) {
            if (!msg) {
              msg = Message.error('Cphone断开连接,请重新登录');
            }
            
            store.commit('call-center/setIsShowModal',false)

            store.commit('call-center/updateCPhoneStatus', 'offline');
            store.commit('call-center/updateLogin', false)
            callState.updateLoginState(false)

            console.log('WebAgent', WebAgent.multiChannelLogout)

            // 隐藏拨号面板
            WebAgent.WaChat.hide();
            // 登出呼叫系统
            WebAgent.multiChannelLogout();
          });
          //与Cphone断开连接
          WebAgent.ChatRegisterEvent('cphoneUnlogged', function (data) {
            if (!msg) {
              msg = Message.error('Cphone断开连接,请重新登录');
            }

            store.commit('call-center/setIsShowModal',false)
            store.commit('call-center/updateCPhoneStatus', 'offline');
            store.commit('call-center/updateLogin', false)
            callState.updateLoginState(false)
            console.log('WebAgent', WebAgent.multiChannelLogout)

            // 隐藏拨号面板
            WebAgent.WaChat.hide();
            // 登出呼叫系统
            WebAgent.multiChannelLogout();

          });
          //与openfire断开连接
          WebAgent.ChatRegisterEvent('openfireDisconnect', function () {
            if (!msg) {
              msg = Message.error('IM服务断开连接，请重新登录')
            }
            // 隐藏拨号面板
            WebAgent.WaChat.hide();
          });
          //电话条位置设置
          WebAgent.WaChat.setPosition({
            top: '63px',
            right: '189px',
            bottom: '100px',
          });
          //判断是否登录
          WebAgent.multiRegisterEvent("login", (data) => {
            msg = null
            console.log('login', data);
            // const type = data.msg?.includes('已登录') ? 'loginSuccess' : data.type
            const type = data.type
            const dataMsg = data.msg ? data.msg.replace(/[0-9]|:/g, '') : ''

            callback?.({ WebAgent, WaChat: WebAgent.WaChat, status: type, msg: dataMsg, awayStatusList: data.params?.awayStatusList })


            // if(data.type === "loginSuccess"){
            //   // 登录之后提示消息中的数字去除
            //   callback?.({ WebAgent, WaChat: WebAgent.WaChat, status: type, msg: dataMsg, awayStatusList: data.params.awayStatusList})
            // }else{
            //   // callback?.({ WebAgent, WaChat: WebAgent.WaChat, status: type, msg: data.msg, awayStatusList: data.params.awayStatusList})
            //   Message.error(data.msg)
            // }

          }, (e) => {
            console.log('multiRegisterEvent', e);
          })

          hasWaInit = true;
          return res(true);
        }
      });
    })
  };

}

export const addDragListener = (chatEle) => {
  if (chatEle) {
    chatEle.addEventListener('mousedown', (e: any) => {
      const ele = document.querySelector('#cchat') as any;
      console.log('event', e);

      const disX = e.clientX - ele.offsetLeft;
      const disY = e.clientY - ele.offsetTop;
      document.onmousemove = (e) => {

        const left = e.clientX - disX;
        const top = e.clientY - disY;

        ele.style.left = left + 'px';
        ele.style.top = top + 'px';
      };
      document.onmouseup = (e) => {
        document.onmousemove = null;
        document.onmouseup = null;
      };
    })
  }
}
